package com.express.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.express.boot.domain.Menu;
import com.express.boot.domain.User_role;
import com.express.boot.mapper.MenuMapper;
import com.express.boot.mapper.User_roleMapper;
import com.express.boot.utils.UserUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
@Transactional
@CacheConfig(cacheNames = "menus_cache")
public class MenuService extends ServiceImpl<MenuMapper, Menu> {
    private final Logger logger = Logger.getLogger(getClass());
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private User_roleMapper user_roleMapper;

    @Cacheable(key = "#root.methodName")
    public List<Menu> getAllMenus() {
        logger.info("权限列表已经存入缓存");
        return menuMapper.getAllMenus();
    }

    @CacheEvict(allEntries = true)
    public boolean updateById(Menu entity) {
        int b = menuMapper.updateById(entity);
        if (b == 0) {
            return false;
        } else {
            logger.info("权限列表已经从缓存中删除删除");
            return true;
        }
    }

    @CacheEvict(allEntries = true)
    public boolean save(Menu entity) {
        int b = menuMapper.insert(entity);
        return b != 0;
    }

    @CacheEvict(allEntries = true)
    public boolean removeById(Serializable id) {
        int i = menuMapper.deleteById(id);
        return i != 0;
    }


    public List<Menu> menuList() {

        QueryWrapper<User_role> query = new QueryWrapper<>();
        query.eq("uid", UserUtil.getCurrentUser().getId());

        User_role user_role = user_roleMapper.selectOne(query);

        return menuMapper.menuListBy(user_role.getRid());

    }

    public List<Menu> allMenuList(String name) {
        return menuMapper.allMenuList(name);
    }
}
